import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import './assets/styles/theme.scss'
import './assets/styles/global.scss'
import App from './App.vue'
import router from './router'
import { wsManager } from './utils/websocket'
import { useChatStore } from './stores/chat'
import { useFriendStore } from './stores/friend'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(router)
app.use(ElementPlus)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 初始化 WebSocket 连接和消息处理
const initWebSocket = () => {
  const chatStore = useChatStore()
  const friendStore = useFriendStore()

  // 连接 WebSocket
  wsManager.connect()

  // 处理聊天消息
  wsManager.onMessage('chat_message', (data: any) => {
    chatStore.receiveMessage({
      id: data.messageId,
      senderId: data.senderId,
      receiverId: data.receiverId,
      content: data.content,
      type: 'text',
      timestamp: new Date(data.timestamp),
      status: 'delivered',
    })
  })

  // 处理好友上线状态
  wsManager.onMessage('friend_online', (data: any) => {
    friendStore.updateFriend(data.userId, { status: 1 })
  })

  // 处理好友离线状态
  wsManager.onMessage('friend_offline', (data: any) => {
    friendStore.updateFriend(data.userId, { status: 0 })
  })

  // 处理好友请求
  wsManager.onMessage('friend_request', (data: any) => {
    friendStore.friendRequests.push({
      id: data.requestId,
      fromUserId: data.fromUserId,
      fromUsername: data.fromUsername,
      fromNickname: data.fromNickname,
      fromAvatar: data.fromAvatar,
      message: data.message,
      status: 'pending',
      timestamp: new Date(data.timestamp),
    })
  })

  // 处理连接状态
  wsManager.on('connected', () => {
    console.log('WebSocket 连接成功')
  })

  wsManager.on('disconnected', () => {
    console.log('WebSocket 连接断开')
  })

  wsManager.on('error', (error: any) => {
    console.error('WebSocket 错误:', error)
  })
}

// 延迟初始化 WebSocket，确保 stores 已经准备好
setTimeout(initWebSocket, 100)

app.mount('#app')
